package com.wangzh.concurrent.lock;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//信号量  模拟排队停车问题，停车场只有3个车位，来了6辆车，只能是先停进来3辆，等3辆车走了剩余的在停进来
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);//代表固定资源个数

        for (int i = 0; i < 6; i++) {
            int finalI = i;
            new Thread(() ->{
                try {
                    semaphore.acquire();

                    System.out.println(finalI +"车停进来了");
//                    TimeUnit.SECONDS.sleep(2);
                    int i1 = new Random().nextInt(5);
                    TimeUnit.SECONDS.sleep(i1);
                    System.out.println(finalI +"车停了"+i1+"秒走了");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }
}
